package com.etc.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.entity.Goods;
import com.etc.entity.Orders;
import com.etc.service.OrdersService;
import com.etc.service.impl.OrdersServiceImpl;
import com.etc.tools.PageData;
import com.etc.tools.ResponseData;
import com.google.gson.Gson;

/**
 * Servlet implementation class UsersController
 */
@WebServlet("/orders.do")
public class OrdersController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	// 带是后台管理
	private OrdersService ordersService = new OrdersServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");

		String op = "query";

		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}

		if ("query".equals(op)) {
			doQuery(request, response);
		}
	}

	protected void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应内容
		response.setContentType("application/json;charset=utf-8");
		String keywords = "";
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}

		int pageNo = 1;

		int pageSize = 10;
		if (request.getParameter("page") != null) {
			pageNo = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("limit") != null) {
			pageSize = Integer.parseInt(request.getParameter("limit"));
		}
		
		// 1 调用service完成查询
		String begindate="";
		String enddate="";
		
		if (request.getParameter("begindate") != null) {
			begindate = request.getParameter("begindate");
		}
		if (request.getParameter("enddate") != null) {
			enddate = request.getParameter("enddate");
		}
		PageData<Orders> pd = ordersService.getByPage(keywords, begindate, enddate, pageNo, pageSize);

		// 2将返回结果转换为json对象 =>ResponseData
		ResponseData<Orders> responseData = new ResponseData<Orders>(0, "操作成功", pd.getTotal(), pd.getData());

		Gson gson = new Gson();
		String result = gson.toJson(responseData);
		// 3 将数据打印返回
		response.getWriter().print(result);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
